import { Injectable } from '@angular/core'
import { Subject, Observable, throwError } from 'rxjs'
import { PUBLIC_URL, SERVER_URL, COMB_URL, COMB_URL2 } from 'app/utils/contraints'
import { HttpClient, HttpParams } from '@angular/common/http'
import { IHttpOptions } from '@shared/interfaces/decorator'
import { map, catchError } from 'rxjs/operators'
import { ObservableStore } from '@shared/classes/ObservableStoreClass'
import { Acquirer, Common, IUpdateAcquirerAudit } from '@shared/interfaces/acquirer'

@Injectable({
  providedIn: 'root'
})
export class CommonAcquirerService {
  private defaultParams = {
    keyword: '',
    limit: 100,
  }

  private acquirers: any[]
  acquirers$ = new Subject<any[]>()

  viewAcquirer$ = new ObservableStore(new Acquirer())

  constructor(
    private http: HttpClient,
  ) {}

  setViewingAcquirer(acquirer: Acquirer) {
    this.viewAcquirer$.setValue(acquirer)
  }

  get viewingAcquirer() {
    return this.viewAcquirer$.value
  }

  queryAcquirers(params = this.defaultParams): Observable<any> {
    const url = `${SERVER_URL}/list`
    const options = this.generateOptions(params)
    const body = {
      codeField: 'insCode',
      colName: 'institution',
      filerMap: {},
      nameField: 'insName'
    }
    return this.http.post<any>(url, body, options).pipe(
      map(res => {
        return this.trans(res)
      }),
      catchError(err => throwError(err))
    )
  }

  getFullAcquirerByInsCode(insCode: string): Observable<Acquirer> {
    const url = `${COMB_URL}/camel/institution/${insCode}/full`
    return this.http.get<Acquirer>(url)
  }

  private trans(acquirers) {
    return acquirers.map(a => {
      return { localName: a.name, label: a.name + '  ' + a.code, value: a.code }
    })
  }

  private generateOptions(params): IHttpOptions {
    let hp = new HttpParams()
    Object.keys(params).forEach(key => hp = hp.append(key, params[key]))
    return {
      params: hp,
      withCredentials: true,
    }
  }

}
